package cn.wyj.org.service.impl;

import cn.wyj.basic.service.impl.BaseServiceImpl;
import cn.wyj.basic.util.PageList;
import cn.wyj.org.domain.Department;
import cn.wyj.org.domain.Department;
import cn.wyj.org.mapper.DepartmentMapper;
import cn.wyj.org.query.DepartmentQuery;
import cn.wyj.org.service.DepartmentService;
import lombok.experimental.Tolerate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;




//    /**
//     * 简单写法
//     * @return
//     */
//    @Override
//    public List<Department> deptTree() {
//        List<Department> allDepts = departmentMapper.findAll();
//        ArrayList<Department> result = new ArrayList<>();
//        // 遍历
//        for (Department dept : allDepts) {
//            if (null == dept.getParentId()) {
//                // 它就是最大的
//                result.add(dept);
//            }else {
//                // 当前的dept是个儿子
//                Long parentId = dept.getParentId();
//                for (Department parent : allDepts) {
//                    if (parent.getId().equals(parentId)){
//                        parent.getChildren().add(dept);
//                        break;
//                    }
//                }
//            }
//        }
//
//
//        return result;
//    }

    @Override
    public List<Department> deptTree() {
        List<Department> allDepts = departmentMapper.findAll();
        // stream流
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));

        ArrayList<Department> result = new ArrayList<>();
        // 遍历
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                // 它就是最大的
                result.add(dept);
            }else {

                Department parent = parentMap.get(dept.getParentId());
                List<Department> children = parent.getChildren();
                children.add(dept);

                // 当前的dept是个儿子
//                Long parentId = dept.getParentId();
//                for (Department parent : allDepts) {
//                    if (parent.getId().equals(parentId)){
//                        parent.getChildren().add(dept);
//                        break;
//                    }
//                }
            }
        }


        return result;
    }
}
